// pages/yunyingzhe/yunyingzhe.js
import Toast from '@vant/weapp/toast/toast';
const { baseURL } = require("../../utils/request")
const http = require("../../api/index")
const api = require("../../api/index")
// const http = require("../../api/camp")
// import { baseURL } from "../../utils/request"
Page({
  data: {
    campConditionList: [], //营位数据列表
    baseURL,
    campImgs: [], //商家信息图片(运营者)
    campConditionList: [], //营位数据列表
    introduce: "", //营地介绍  
    facilitiesList:[],//服务设施列表
    selectFacilitiesList:[],//选中服务设施列表
    oss_url:baseURL,
    name: "", //名称
    open: false, //选择器状态
    latitude: "", //维度
    longitude: "", //经度
    campLocation: "", //位置
    address: "", //详细地址信息
    timeOpen: false, //控制时间选择的开关
    timeDetailOpen: false, //控制月份选择器
    time: "", //营业时间
    value:'',
    active: 0,
    show: false,
    showType: false,
    showTime:false,
    campLocation: "",
    fieldValue: '',
    campType: "",
    yingyetime:"",
    cascaderValue: '',
    columns: ['常规营地', '微型营地', '无人值守驻车点'],
    columnss:['全年','月份'],
    serviceFacilitiesList: [],
    steps: [
      {
        text: '营地信息',
      },
      {
        text: '服务设施',
      },
      {
        text:'营地介绍',
      }
      ],
  },
  onConfirmType(event) {
    const { picker, value, index } = event.detail;
    Toast(`当前值：${value}, 当前索引：${index}`);
    this.setData({
      campType: value,
      showType: false
    })
  },
  onConfirmTime(event) {
    const { picker, value, index } = event.detail;
    Toast(`当前值：${value}, 当前索引：${index}`);
    this.setData({
      yingyetime: value,//回填
      campTime: value,
      showTime: false
    })
  },
  onCancelType() {
    Toast('取消');
  },
  onCancelTime() {
    Toast('取消');
  },
  //基本的输入框
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
  },
  //级联输入框营地类型
  onClickType() {
    this.setData({
      showType: true,
    });
  },
  onClickTime() {
    this.setData({
      showTime: true,
    });
  },
  //营地类型设置内容
  onCloseType() {
    this.setData({
      show: false,
    });
  },
  onCloseTime() {
    this.setData({
      show: false,
    });
  },
  onNext() {
    let _active = this.data.active + 1;
    this.setData({
      active: _active  
    })
  },
  onBack() {
    let _active = this.data.active - 1;
    this.setData({
      active: _active  
    })
  },
    //获取图片
    getUploadList(l) {
      console.log(l)
      this.setData({
        campImgs: l.detail,
        tourisCampImgs: l.detail
      })
    },
    //删除图片
    delImgs(u) {
      this.data.campImgs.splice(u.currentTarget.dataset.index, 1)
      this.setData({
        campImgs: this.data.campImgs
      })
    },
// 营地位置
selectSite() {
  // 检查用户权限状态
  wx.getSetting({
    success: res => {
      if (!res.authSetting['scope.userLocation']) {
        // 用户尚未授权或已拒绝授权
        // 主动请求授权
        this.requestLocationAuthorization();
      } else {
        // 已经授权，直接获取位置信息
        this.getUserLocation();
      }
    }
  })
},
//获取位置信息
getUserLocation() {
  wx.getLocation({
    // type: 'wgs84',
    type: 'gcj02',
    success: (res) => {
      console.log(res, "返回的数据")
      this.setData({
        latitude: res.latitude,
        longitude: res.longitude,
      });
      wx.chooseLocation({
        longitude: this.data.longitude,
        latitude: this.data.latitude,
        success: (res) => {
          console.log(res, '########');
          this.setData({
            latitude: res.latitude,
            longitude: res.longitude,
            campLocation: res.address
          });
        },
        fail: err => {
          console.log(err)
        }
      })
    },
    fail: (err) => {
      console.error('获取位置失败:', err);
    },
    complete: () => {
      console.log('位置获取操作已完成');
    }
  });
},
// 请求授权
requestLocationAuthorization() {
  // 请求用户授权精确位置
  wx.authorize({
    scope: 'scope.userLocation',
    success: () => {
      this.getUserLocation();
    },
    fail: (err) => {
      // 拒绝授权，提示用户收到开启
      this.showSettingPrompt()
    }
  })
},
showSettingPrompt() {
  wx.showModal({
    title: '需要位置权限',
    content: '请在设置中开启位置权限以正常使用本功能。',
    showCancel: false,
    confirmText: '去设置',
    success: (res) => {
      if (res.confirm) {
        wx.openSetting({
          success: (settingRes) => {
            if (settingRes.authSetting['scope.userLocation']) {
              // 用户在设置中开启了位置权限
              this.getUserLocation();
            } else {
              // 用户仍然拒绝位置权限
              console.log('用户仍未开启位置权限');
            }
          },
        });
      }
    },
  });
},
//图片上传
picture(){
  wx.chooseImage({
    success (res) {
      const tempFilePaths = res.tempFilePaths
      wx.uploadFile({
         url:'https://example.weixin.qq.com/upload', //仅为示例，非真实的接口地址
         filePath: tempFilePaths[0],
         name: 'file',
         formData: {
           'user': 'test'
         },
         success (res){
           const data = res.data
           //do something
         }
      })
    }
   })
},
//服务设施
async getFacilitiesList(){
  const res= await HTMLOutputElement.serviceFacilites()
  this.setData({
    facilitiesList:res.data
  })
  console.log(res)
},

onLoad(options){
  this.setData({
    userType: options.userType
  })
  this.getFacilitiesList()
},
//获取服务设施
async getFacilitiesList(){
  const res = await http.serviceFacilities()
  this.setData({
    facilitiesList:res.data
  })
  console.log(res)
},
//选中服务设施
selectIcon(e){
  let a, b, select, list, id, data
  list = this.data.facilitiesList
  id = e.currentTarget.dataset.id
  data = this.data.serviceFacilitiesList
  for(let i = 0;i<list.length;i++){
    for(let j = 0;j<list[i].facilities.length;j++){
      if(id==list[i].facilities[j].facilityId){
        a=i
        b=j
      }
    }
  }
  select = list[a].facilities[b].state
  //如果没有选中
  if(select==1){
    list[a].facilities[b].state=2
    data.push(id)
    this.setData({
      facilitiesList: list,
      serviceFacilitiesList: data
    })
  }else{
    list[a].facilities[b].state=1
    let index = data.indexOf(id)
    data.splice(index,1)
    this.setData({
      facilitiesList: list,
      selectFacilitiesList:data
    })
  }
},
  // 绑定营地介绍
  changeIntroduce(e) {
    this.setData({
      introduce: e.detail.value
    })
  },

      // 营位
  toCampType() {
    this.setData({
      campCondotionStatus: true,
    })
  },
  // 获取营位
  getCampCampsite() {
    api.getCampCampsite(this.data.campId).then(res => {
      console.log(res)
      if (res.code == 200 && res.data) {
        this.setData({
          campConditionList: res.data
        })
      }
    })
  },
    //营位选择数据
    campConditionList(e) {
      this.setData({
        campConditionDatas: e.detail,
        touristConditionData: e.detail
      })
      const campSite = this.data.campConditionDatas
      const index = campSite.length - 1
      // 添加
      const result = campSite.map(item => {
        item.factor = item.factorId?.join(",")
        item.campId = this.data.campId
        return item
      })
      const object = result[index]
      var isEmpty = true;
      Object.keys(object).forEach(function (x) {
        if (object[x] === null || object[x] === "") {
          isEmpty = false;
        }
      });
      if (isEmpty) {
        http.campAddCampsite([result[index]]).then((res) => {
          if (res.code === 200) {
            wx.showToast({
              title: '提交成功',
              icon: 'none',
              duration: 1500
            })
            this.getCampCampsite()
          }
        })
      }
    },
      // 删除营位
  delCondition(event) {
    Dialog.confirm({
        title: '营位删除',
        message: '确定删除该营位吗？',
      })
      .then(() => {
        console.log(event.currentTarget)
        http.campDelCampsite(event.currentTarget.dataset.id).then(res => {
          console.log(res)
          if (res.code == 200) {
            this.getCampCampsite()
          }
        })
      })
      .catch(() => {
      });
  },
    // 商家提交数据
    async businessSub() {
      await this.subCamp()
      await this.subService()
    },
    // 提交营地信息
  async subCamp() {
    let userInfo = wx.getStorageSync("userInfo")
    let campType = this.campType(this.data.type)
    let res = await http.addCamp({
      userId: userInfo.userId,
      userType: this.data.userType,
      campType,
      campName: this.data.name,
      longitude: this.data.longitude, //经度
      latitude: this.data.latitude,
      location: this.data.campLocation,
      address: this.data.address,
      timeType: this.data.yingyetime,
      specificTime: this.data.time,
      linkman: this.data.contacts,
      phone: this.data.phone,
      imageUrl: this.data.campImgs.join(","),
      introduce: this.data.introduce,
      campUser: {
        userId: userInfo.userId
      }
    })
    this.setData({
      campId: res.msg
    })
  },
  // 上传服务设施
  async subService() {
    let res = await http.addService({
      campId: this.data.campId,
      facilityIds: this.data.selectFacilitiesList
    })
    console.log(res)
    if (res.code == 200) {
      wx.redirectTo({
        url: `../detail/detail?campId=${this.data.campId}`,
      })
    }
  }, 
    // 返回营地类型id
    campType(value) {
      return this.data.campTypes.indexOf(value) + 1
    },
      // 选中服务设施
  selectIcon(e) {
    let a, b, select, list, id, data
    list = this.data.facilitiesList
    id = e.currentTarget.dataset.id
    data = this.data.selectFacilitiesList
    for (let i = 0; i < list.length; i++) {
      for (let j = 0; j < list[i].facilities.length; j++) {
        if (id == list[i].facilities[j].facilityId) {
          a = i
          b = j
        }
      }
    }
    select = list[a].facilities[b].state
    // 如果没有选中，则选中
    if (select == 1) {
      list[a].facilities[b].state = 2
      data.push(id)
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data
      })
    } else {
      // 已经选中，则取消选中
      list[a].facilities[b].state = 1
      let index = data.indexOf(id)
      data.splice(index, 1)
      this.setData({
        facilitiesList: list,
        selectFacilitiesList: data
      })
    }

    console.log(this.data.selectFacilitiesList);
  },
})